<?php
namespace Admin\Model;
use Think\Model;
use Admin\Model\RoleModel;

class ManageModel extends Model
{
	// 模型字段
	protected $fields = array(
		"manage_id",				// 管理员id
		"username",					// 用户名
		"password",					// 密码
		"email",					// 邮箱
		"sex",						// 性别：0女，1男
		"status",					// 状态：0正常，1被封禁
		"user_add_time",			// 创建时间
		"description",				// 描述
		"role_id",					// 角色id
		"auth",						// 角色权限:0超级管理员，1普通
		"is_del"					// 删除：0正常，1被删除
	);
	
	// 主键
	protected $pk     = 'manage_id';
	
	// 查询
	public function selList($page,$limit,$order_field,$order_type,$username)
	{
		$where = array(
			'is_del' => 0
		);
		if (!empty($username)) {
			$where['username'] = array('like',"%$username%");
		}
		$order = array(
			'manage_id' => 'desc'
		);
		if (!empty($order_field) && $order_type) {
			$order["$order_field"] = $order_type;
		}
		$count = $this->where($where)->count();
		$u_list = $this->where($where)->order($order)->limit(($page-1)*$limit.','.$limit)->select();
		$temp = array();
		foreach ($u_list as $key => $manage_user) {
			$temp[$key] = $manage_user;
			$temp[$key]["role"] = (new RoleModel)->getRoleById($manage_user["role_id"]);
		}
		return array(
			'code' => 0,
			'msg' => '',
			'count' => $count,
			'data' => $temp
		);
	}
	
	// 按用户查询
	public function selByName($username)
	{
		$where = array(
			'is_del' => 0,
			'username' => $username,
			'del_del' => 1
		);
		$result = $this->where($where)->find();
		return $result;
	}

	// 按id查询
	public function selById($manage_id)
	{
		$where = array(
			'is_del' => 0,
			'manage_id' => $manage_id
		);
		$result = $this->where($where)->find();
		return $result;
	}

	// 删除
	public function del($manage_id) {
		if ($manage_id > 0) {
			$data['is_del'] = 1;
			$result = $this->where("manage_id = $manage_id")->save($data);
			return $result;
		}
	}

	// 批量删除
	public function delAll($manage_ids)
	{
		$result = 0;
		foreach ($manage_ids as $key => $value) {
			$this->del($value);
			$result++;
		}
		return $result;
	}

	// 新增
	public function addIt($data)
	{
		$data['user_add_time'] = strtotime($data['user_add_time']);
		$data['password'] = md5($data['password']);
		$result = $this->add($data);
		return $result;
	}

	// 编辑
	public function updIt($data)
	{
		if ($data['manage_id'] > 0) {
			$data['user_add_time'] = strtotime($data['user_add_time']);
			$result = $this->save($data);
			return $result;
		}
	}

	// 重置密码
	public function pass($manage_id) {
		if ($manage_id > 0) {
			$data['password'] = md5('123456');
			$result = $this->where("manage_id = $manage_id")->save($data);
			return $result;
		}
	}

	// 修改密码
	public function updpwd($data){
		if ($data["manage_id"] > 0) {
			$result = $this-> where(array("manage_id"=>$data["manage_id"]))->setField('password',$data["password"]);
			return $result;
		}
	}
}